<?php
/*
 * 这段脚本需要放置在入口文件的最上面，才能对整个页面周期进行数据收集和分析（含CPU时间）。
 * 本XHPROF脚本需求：php >= 5.2.0，UNIX，xhprof
 * 请注意：根据xhprof说明，CPU时间和特定服务器有关
 * 使用前：
 *   请先配置函数xweibo_xhprof_save内的$_xhprofSaveConfig变量。
 *   由于使用了register_shutdown_function调用xhprof保存数据，
 *   故$_xhprofSaveConfig变量内涉及目录的地方，务必使用绝对路径！
 * @author Horse Luke
 * @since 2011-02-19
 * @version $Id: xhprof_header_hook.php 168 2011-03-07 03:31:10Z horseluke@126.com $
 */
//xhprof脚本内容开始
xhprof_enable( XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY );
register_shutdown_function( 'xweibo_xhprof_save' );


function xweibo_xhprof_save(){
    //xweibo_xhprof config
    static $_xhprofSaveConfig = array(
            'lib_root' => "/var/www", //Where is the dir 'xhprof_lib' located?
            'namespace' => 'xweibo',  //the profile namespace
            'view_url' => 'http://ubuntu.xweibo.com/xhprof_html',  //the url that can run xhprof view
            'view_url_log_filepath' => '/var/www/xweibo/xhprofviewurl.txt',    //WHERE TO LOG THE xhprof view url?
    );

    // stop profiler
    $xhprof_data = xhprof_disable();

    // Saving the XHProf run
    // using the default implementation of iXHProfRuns.
    include_once $_xhprofSaveConfig['lib_root'] . "/xhprof_lib/utils/xhprof_lib.php";
    include_once $_xhprofSaveConfig['lib_root'] . "/xhprof_lib/utils/xhprof_runs.php";
    $xhprof_runs = new XHProfRuns_Default();

    // Save the run under a namespace $_xhprofSaveConfig['namespace'].
    //
    // **NOTE**:
    // By default save_run() will automatically generate a unique
    // run id for you. [You can override that behavior by passing
    // a run id (optional arg) to the save_run() method instead.]
    $run_id = $xhprof_runs->save_run( $xhprof_data, $_xhprofSaveConfig['namespace'] );


    $viewurl = $_xhprofSaveConfig['view_url'] . "/index.php?run={$run_id}&source={$_xhprofSaveConfig['namespace']}";
    $datetime = date( "Y-m-d H:i:s" );
    $requestUri = xweibo_current_requestUri();
    $logText = "{$datetime}\t{$run_id}\t{$viewurl}\t{$requestUri}\n\r";
    file_put_contents( $_xhprofSaveConfig['view_url_log_filepath'], $logText, FILE_APPEND );

    /*
    $displayText = "---------------\n".
    "Assuming you have set up the http based UI for \n".
    "XHProf at some address, you can view run at \n".
    "{$viewurl}\n".
    "---------------\n";
    echo $displayText;
	*/

}


function xweibo_current_requestUri(){
    if (isset( $_SERVER['REQUEST_URI'] )) {
        return $_SERVER['REQUEST_URI'];
    } elseif (isset( $_SERVER['PHP_SELF'] )) {
        if (isset( $_SERVER['argv'] )) {
            return $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
        } elseif (isset( 
        $_SERVER['QUERY_STRING'] )) {
            return $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        } else {
            return $_SERVER['PHP_SELF'];
        }
    } else {
        return '__UNKNOWN_REQUEST_URI__';
    }
}

//xhprof脚本内容结束